package com.aliware.tianchi;


import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.rpc.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;


/**
 * 客户端过滤器（选址后）
 * 可选接口
 * 此类可以修改实现，不可以移动类或者修改包名
 * 用户可以在客户端拦截请求和响应,捕获 rpc 调用时产生、服务端返回的已知异常。
 */
@Activate(group = CommonConstants.CONSUMER)
public class TestClientFilter implements Filter, BaseFilter.Listener {
    @Override
    public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
        try {
            Result result = invoker.invoke(invocation);
            return result;
        } catch (Exception e) {
            throw e;
        }


    }
    //利用连续失败的时间判断离线 请求成功后恢复
    @Override
    public void onResponse(Result appResponse, Invoker<?> invoker, Invocation invocation) {
        int avgSpendTime = Integer.parseInt(appResponse.getAttachment("avgSpendTime"));
        int len = Integer.parseInt(appResponse.getAttachment("len"));
        long avgSpendDuringSecond = Long.parseLong(appResponse.getAttachment("avgTimeDuringSecond"));
        if (avgSpendDuringSecond > 100) {
            avgSpendDuringSecond = 50 ;
        }


        long [] count = new long[GatewayManager.BUCKETNUM];
        String key = "";
        for (int i = 0; i < GatewayManager.BUCKETNUM; i++) {
            key = "count" + i;
            count[i] = Long.parseLong(appResponse.getAttachment(key));
            if (count[i] > 100) {
                count[i] = 50 + count[i] % 20;
            }
        }
        int activate = Integer.parseInt(appResponse.getAttachment("activate"));
        GatewayManager.updateProviderInfo(invoker.getUrl().getAddress(), avgSpendTime, activate, avgSpendDuringSecond, len, count);
        int max = Integer.parseInt(appResponse.getAttachment("max"));
        GatewayManager.getProviderInfo(invoker).setMax(new AtomicInteger(max));
        AtomicLong now = new AtomicLong(System.currentTimeMillis());
        GatewayManager.getProviderInfo(invoker).setLastActiveTime(now);
    }


    @Override
    public void onError(Throwable t, Invoker<?> invoker, Invocation invocation) {
    }


}
